package com.cml.domain.factory;

import com.cml.domain.entity.Message;
import com.cml.domain.entity.ServerNode;

import java.io.DataInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;

/**
 * 姓名：陈茂林
 * 时间：2023/10/11 8:49
 * 描述：
 */
public class RemoteServerNodeMessageBuilderFactory extends  MessageBuilderFactory{


    @Override
    public Message doBuildMessage(DataInputStream dataInputStream) throws IOException {
        ServerNode remoteServerNode = new ServerNode();
        remoteServerNode.setId(dataInputStream.readInt());
        //ip地址长度
        Integer ipLen = dataInputStream.readInt();
        byte[] ipByte = new byte[ipLen];
        dataInputStream.read(ipByte);
        remoteServerNode.setIp(new String(ipByte));
        remoteServerNode.setPort(dataInputStream.readInt());
        remoteServerNode.setFollower(dataInputStream.readBoolean());
        remoteServerNode.setLeader(dataInputStream.readBoolean());
        remoteServerNode.setServiceManagerPort(dataInputStream.readInt());
        return remoteServerNode;
    }

    @Override
    public void doMessageBuilder(ByteBuffer byteBuffer, Message message) throws IOException {
        ServerNode remoteServerNode = (ServerNode) message;
        byteBuffer.putInt(remoteServerNode.getId());
        byteBuffer.putInt(remoteServerNode.getIp().length());
        byteBuffer.put(remoteServerNode.getIp().getBytes());
        byteBuffer.putInt(remoteServerNode.getPort());
        byteBuffer.put(remoteServerNode.isFollower() ? (byte)1 : (byte)0);
        byteBuffer.put(remoteServerNode.isLeader() ? (byte)1 : (byte)0);
        byteBuffer.putInt(remoteServerNode.getServiceManagerPort());
    }




}
